package com.sukaiyi.generator.processor;

import com.sukaiyi.generator.actions.model.ActionContext;
import com.sukaiyi.generator.config.model.StructTemplate;
import com.sukaiyi.generator.config.model.TplType;
import com.sukaiyi.generator.utils.PsiClassUtils;
import com.sukaiyi.generator.utils.PsiDirectoryUtils;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;

import java.util.List;

public class PersistenceProcessor {
    private static final PersistenceProcessor INSTANCE = new PersistenceProcessor();

    private PersistenceProcessor() {
    }

    public static PersistenceProcessor getInstance() {
        return INSTANCE;
    }

    public void process(ActionContext actionContext, StructTemplate template) {
        List<StructTemplate> children = template.getChildren();
        assert children != null && children.size() > 0;
        persistence(actionContext.getDirectory(), children);
    }

    private void persistence(PsiDirectory directory, List<StructTemplate> templates) {
        if (templates == null || templates.size() == 0) {
            return;
        }
        for (StructTemplate structTemplate : templates) {
            if (structTemplate.getType() == TplType.MODULE) {
                persistence(PsiDirectoryUtils.getChildByName(directory, structTemplate.getName()), structTemplate.getChildren());
            } else if (structTemplate.getType() == TplType.TEMPLATE) {
                PsiFile file = PsiFileFactory.getInstance(directory.getProject()).createFileFromText(structTemplate.getName(), JavaFileType.INSTANCE, structTemplate.getContent());
                if (file instanceof PsiJavaFile) {
                    PsiJavaFile javaFile = (PsiJavaFile) file;
                    PsiClass[] classes = javaFile.getClasses();
                    for (PsiClass aClass : classes) {
                        PsiClassUtils.format(aClass);
                    }
                }
                try {
                    directory.add(file);
                } catch (IncorrectOperationException e) {

                }
            }
        }
    }
}
